package com.yinxin.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

//通过反射构造对象和对对象赋值
public class TestCreateClass {
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        //获得Class对象
        Class UserClazz = Class.forName("com.yinxin.reflection.User");
        //构造对象
//        User user = (User) UserClazz.newInstance();
//        System.out.println(user);
        //通过构造器创建对象
//        Constructor constructor = UserClazz.getDeclaredConstructor(int.class, String.class, String.class);
//        User allArgsUser = (User)constructor.newInstance(19, "尹鑫", "男");
//        System.out.println(allArgsUser);
        //通过反射调用普通方法
        User user = (User) UserClazz.newInstance();
        //通过反射获取一个方法
        Method setName = UserClazz.getDeclaredMethod("setName", String.class);
        setName.invoke(user,"小静");//invoke激活的意思，(对象,"方法的值")
        System.out.println(user.getName());
        //通过反射操作属性
        User user1 = (User)UserClazz.newInstance();
        Field name = UserClazz.getDeclaredField("name");//Class com.yinxin.reflection.TestCreateClass can not access a member of class com.yinxin.reflection.User with modifiers "private"
        //此时报错:name是私有变量无法访问
        name.setAccessible(true);//取消该属性的安全检测
        name.set(user1,"小静2");
        System.out.println(user1.getName());
    }
}
